<template>
  <div>
    <van-pull-refresh v-model="isLoading" @refresh="onRefresh" :disabled='finished'>
      <van-list v-model="loading" :finished="finished" finished-text="没有更多了" @load="onLoad" offset="50" :immediate-check="false">
        <!-- 文章列表 -->
        <article-item v-for="item in val" :key="item.art_id" :obj="item" @dislike="dislikeFn" @click.native="$router.push(`/article/${item.art_id}`)"></article-item>
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
// import { Notify } from 'vant'
import ArticleItem from '@/components/Aticleitrm.vue'
import { articlesListAPI } from '@/api/home.js'
import { MyNotify } from '@/utils/Notify.js'
export default {
  data() {
    return {
      val: [], // 文章列表
      loading: false, // 底部加载状态
      finished: false, // 数据是否全部加载完成
      pretimestamp: Date.now(), // 记录上一次的时间戳发送给后端接口
      isLoading: false // 没有处于下拉状态
    }
  },
  props: {
    chnId: {
      type: Number,
      default: 0
    }
  },
  components: {
    ArticleItem
  },
  async created() {
    // const resp = await articlesListAPI({
    //   channelId: this.chnId
    // })
    // this.val = resp.data.data.results
    // console.log(this.val)
    this.getAticleList()
  },
  methods: {
    onLoad() {
      if (this.val.length > 0) {
        this.getAticleList()
      }
    },
    async getAticleList() {
      const resp = await articlesListAPI({
        channelId: this.chnId,
        timestamp: this.pretimestamp
      })
      console.log(resp)
      const { pre_timestamp, results } = resp.data.data
      this.pretimestamp = pre_timestamp
      console.log(this.val)
      // 如果无数据,从这添加拉取
      if (results.length < 10 || pre_timestamp === null) {
        this.finished = true // 告诉list组件直接底部显示没有更多数据
      } else {
        this.val = [...this.val, ...results]
        // 等待网络请求结果后
        this.loading = false // 底部加载更多状态
      }
    },
    async onRefresh() {
      const resp = await articlesListAPI({
        channelId: this.chnId,
        timestamp: this.pretimestamp
      })
      if (resp.data.data.results.length < 10 || resp.data.datapre_timestamp === null) {
        // 告诉list组件直接顶部显示没有更多数据
        this.isLoading = false
        MyNotify({ type: 'warning', message: '没有更多数据了别拉了再拉就拉伤了' })
        this.finished = true
      } else {
        this.val = resp.data.data.results
        // 等待网络请求结果后
        this.isLoading = false // 恢复可以加载更多状态
      }
      console.log(resp.data.data, this.finished)
    },
    dislikeFn(obj) {
      // 想实现删除不感兴趣对应的文章，通过子传递父寻找到反馈的文章ID和文章列表中ID相同的文章元素的下标
      const index = this.val.findIndex(item => item.art_id === obj.art_id)
      index !== -1 && this.val.splice(index, 1)
    }
  }
}
</script>
